package com.zwcl.common.web.handler;

import com.zwcl.common.core.domain.entity.ApiResult;
import com.zwcl.common.core.enums.ExceptionCode;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.proxy.MethodInterceptor;
import feign.FeignException;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 统一降级方法的处理
 * 还没有测试过(测试后，发现，feign调用没有用到这边的处理)
 * 只在feign调用时生效！如果某个服务限流，直接调用到该服务上，这个是不起作用！
 * xyp
 * @param <T>
 */
@Slf4j
@AllArgsConstructor
public class FunFeignFallback<T> implements MethodInterceptor {
    private final Class<T> targetType;
    private final String targetName;
    private final Throwable cause;

    @Nullable
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        String errorMessage = cause.getMessage();
        log.error("FunFeignFallback:[{}.{}] serviceId:[{}] message:[{}]", targetType.getName(), method.getName(), targetName, errorMessage);
        // 非 FeignException，直接返回
        if (!(cause instanceof FeignException)) {
            //此处只是示例，具体可以返回带有业务错误数据的对象
            return ApiResult.fail(cause.getMessage());
        }
        FeignException exception = (FeignException) cause;
        //此处只是示例，具体可以返回带有业务错误数据的对象
        return ApiResult.fail(ExceptionCode.REQUEST_DEGRADE_LIMITER.getCode(),"服务限流降级："+ exception.getMessage());
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        FunFeignFallback<?> that = (FunFeignFallback<?>) o;
        return targetType.equals(that.targetType);
    }

    @Override
    public int hashCode() {
        return Objects.hash(targetType);
    }
}